package com.tanhua.server.controller;

import com.tanhua.model.domain.UserInfo;
import com.tanhua.server.service.UserInfoService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.tanhua.commons.utils.JwtUtils;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 保存用户信息
     *   UserInfo
     *   请求头中携带token
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo,
                                       @RequestHeader("Authorization") String token) {
        //1、判断 token是否合法
        if (!JwtUtils.verifyToken(token)) {
            return ResponseEntity.status(401).body(null);
        }
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");
        //2、向userinfo中设置用户id
        userInfo.setId(Long.valueOf(id));
        //3、调用service
        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);
    }


    /**
     * 头像
     *   UserInfo
     *   请求头中携带token
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto,
                                       @RequestHeader("Authorization") String token) {

        //1、判断 token是否合法
        if (!JwtUtils.verifyToken(token)) {
            return ResponseEntity.status(401).body(null);
        }

        //1、解析token
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");

        userInfoService.update(headPhoto,id);

//        //2、向userinfo中设置用户id
//        UserInfo userInfo = new UserInfo();
//        userInfo.setId(Long.valueOf(id));
//        //3、调用service
//        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }

    }